<template>
  <div class="history-container">
    <!-- 工单统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon cleaning-icon">
              <el-icon><Finished style="font-size: 20px" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">累计完成订单</div>
              <div class="stat-value">{{ stats.totalCompleted }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon star-icon">
              <el-icon><Star style="font-size: 20px" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">已获得评价</div>
              <div class="stat-value">{{ stats.totalRated }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon rating-icon">
              <el-icon><StarFilled style="font-size: 20px" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">平均评分</div>
              <div class="stat-value">{{ stats.averageRating.toFixed(1) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <h2>历史记录</h2>
              <div class="header-actions">
                <el-select v-model="filterStatus" placeholder="状态" size="small" style="width: 100px; margin-right: 10px">
                  <el-option label="全部" value="" />
                  <el-option label="已完成" value="已完成" />
                  <el-option label="已评价" value="已评价" />
                </el-select>
                <el-select v-model="ratingFilter" placeholder="评分" size="small" style="width: 100px; margin-right: 10px">
                  <el-option label="全部" value="" />
                  <el-option label="5星" value="5" />
                  <el-option label="4星" value="4" />
                  <el-option label="3星" value="3" />
                  <el-option label="2星" value="2" />
                  <el-option label="1星" value="1" />
                  <el-option label="未评分" value="0" />
                </el-select>
                <el-button type="success" size="small" @click="fetchCompletedTasks">查询</el-button>
                <el-button size="small" @click="resetFilters">重置</el-button>
              </div>
            </div>
          </template>

          <el-table :data="completedTasks" border style="width: 100%" v-loading="loading" height="500">
            <el-table-column prop="completed_time" label="完成时间" width="180" sortable />
            <el-table-column prop="expected_service_date" label="服务日期" width="120" />
            <el-table-column prop="expected_time_slot" label="时间段" width="100" />
            <el-table-column label="特殊要求" show-overflow-tooltip width="230">
              <template #default="scope">
                {{ scope.row.special_requirements || scope.row.content || '标准保洁' }}
              </template>
            </el-table-column>
            <el-table-column prop="address" label="服务地址" width="200" show-overflow-tooltip />
            <el-table-column prop="rating" label="评分" width="150" align="center" sortable>
              <template #default="scope">
                <el-rate v-model="scope.row.rating" disabled size="small" v-if="scope.row.rating > 0"/>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.status === '已评价' ? 'success' : 'info'">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="viewTaskDetail(scope.row)" type="success" text>查看</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="[10, 20, 30, 50]"
              :total="total"
              :page-size="pageSize"
              :current-page="currentPage"
              @size-change="handleSizeChange"
              @current-page-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 单个工种的详细统计 -->
    <!-- <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <h3>保洁任务统计</h3>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="stat-box">
                <div class="stat-box-title">本月完成</div>
                <div class="stat-box-value">{{ stats.monthlyCompleted }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-box">
                <div class="stat-box-title">本周完成</div>
                <div class="stat-box-value">{{ stats.weeklyCompleted }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-box">
                <div class="stat-box-title">好评率</div>
                <div class="stat-box-value">{{ stats.goodRatingPercentage }}%</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row> -->
  </div>

  <!-- 任务详情对话框 -->
  <el-dialog
    v-model="detailDialogVisible"
    title="保洁任务详情"
    width="600px"
  >
    <el-descriptions :column="1" border>
      <el-descriptions-item label="任务编号">{{ currentTask.id }}</el-descriptions-item>
      <el-descriptions-item label="服务日期">{{ currentTask.expected_service_date }}</el-descriptions-item>
      <el-descriptions-item label="服务时间段">{{ currentTask.expected_time_slot || '全天' }}</el-descriptions-item>
      <el-descriptions-item label="特殊要求">{{ currentTask.special_requirements || currentTask.content || '标准保洁' }}</el-descriptions-item>
      <el-descriptions-item label="服务地址">{{ currentTask.address }}</el-descriptions-item>
      <el-descriptions-item label="联系人">{{ currentTask.contact_name || '无' }}</el-descriptions-item>
      <el-descriptions-item label="联系电话">{{ currentTask.contact_phone || '无' }}</el-descriptions-item>
      <el-descriptions-item label="房间面积" v-if="currentTask.room_area">{{ currentTask.room_area }} 平方米</el-descriptions-item>
      <el-descriptions-item label="保洁类型" v-if="currentTask.cleaning_type">{{ currentTask.cleaning_type }}</el-descriptions-item>
      <el-descriptions-item label="完成时间">{{ currentTask.completed_time }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="currentTask.status === '已评价' ? 'success' : 'info'">{{ currentTask.status }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="用户评分">
        <el-rate v-model="currentTask.rating" disabled v-if="currentTask.rating > 0"/>
        <span v-else>暂无评分</span>
      </el-descriptions-item>
      <el-descriptions-item label="评价内容">{{ currentTask.review_content || '暂无评价' }}</el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Finished, Star, Money, StarFilled, Brush } from '@element-plus/icons-vue';
import { dashboardService } from '@/api/tasks';

export default {
  name: 'CleaningHistory',
  components: {
    Finished,
    Star,
    Money,
    StarFilled,
    Brush
  },
  setup() {
    const router = useRouter();
    const loading = ref(false);
    const completedTasks = ref([]);
    const total = ref(0);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const filterStatus = ref('');
    const ratingFilter = ref('');
    const filterType = ref('cleaning');
    
    // 详情对话框
    const detailDialogVisible = ref(false);
    const currentTask = ref({});

    // 统计数据
    const stats = reactive({
      totalCompleted: 0,
      totalRated: 0,
      averageRating: 0,
      monthlyCompleted: 0,
      weeklyCompleted: 0,
      goodRatingPercentage: 0
    });

    // 获取已完成任务列表
    const fetchCompletedTasks = async () => {
      loading.value = true;
      try {
        const params = {
          page: currentPage.value,
          pageSize: pageSize.value,
          type: 'cleaning'
        };

        const { data } = await dashboardService.getCompletedTasks(params);
        if (data.code === 200) {
          // 获取原始数据
          let rawData = data.data.list || data.data;
          
          // 过滤出保洁任务
          rawData = rawData.filter(task => task.type === 'cleaning');
          
          // 处理每个任务的数据，确保字段一致性
          rawData = rawData.map(task => {
            return {
              ...task,
              // 确保联系人和联系电话字段存在
              contact_name: task.contact_name || task.contactName || task.applicant_name || '未指定',
              contact_phone: task.contact_phone || task.contactPhone || task.applicant_phone || '未指定',
              // 确保其他关键字段存在
              expected_service_date: task.expected_service_date || task.expectedServiceDate || '未指定',
              expected_time_slot: task.expected_time_slot || task.expectedTimeSlot || '全天',
              special_requirements: task.special_requirements || task.specialRequirements || '标准保洁服务',
              address: task.address || task.unit_info || task.unitInfo || '未指定',
              completed_time: task.completed_time || task.completionTime || task.completion_time || '未指定',
              rating: task.rating || 0,
              review_content: task.review_content || task.reviewContent || ''
            };
          });
          
          // 前端筛选逻辑
          let filteredData = rawData;
          
          // 按状态筛选
          if (filterStatus.value) {
            filteredData = filteredData.filter(task => task.status === filterStatus.value);
          }
          
          // 按评分筛选
          if (ratingFilter.value) {
            const ratingValue = parseInt(ratingFilter.value);
            if (ratingValue === 0) {
              // 筛选未评分的任务
              filteredData = filteredData.filter(task => !task.rating || task.rating === 0);
            } else {
              // 筛选特定评分的任务
              filteredData = filteredData.filter(task => task.rating === ratingValue);
            }
          }
          
          // 更新数据和总数
          completedTasks.value = filteredData;
          total.value = filteredData.length;
          
          // 计算统计数据
          calculateStats();
        } else {
          ElMessage.error(data.message || '获取历史记录失败');
        }
      } catch (error) {
        console.error('获取历史记录失败:', error);
        ElMessage.error('获取历史记录失败');
      } finally {
        loading.value = false;
      }
    };

    // 计算统计数据
    const calculateStats = () => {
      // 基础统计
      stats.totalCompleted = total.value;
      
      // 只计算当前页面的评分统计
      const ratedTasks = completedTasks.value.filter(task => task.rating > 0);
      stats.totalRated = ratedTasks.length;
      
      // 计算平均评分
      stats.averageRating = ratedTasks.length > 0 
        ? ratedTasks.reduce((sum, task) => sum + task.rating, 0) / ratedTasks.length 
        : 0;
      
      // 计算时间相关统计
      const now = new Date();
      const currentMonth = now.getMonth();
      const currentYear = now.getFullYear();
      
      // 本月完成的任务
      stats.monthlyCompleted = completedTasks.value.filter(task => {
        if (!task.completed_time) return false;
        const completedDate = new Date(task.completed_time);
        return completedDate.getMonth() === currentMonth && 
               completedDate.getFullYear() === currentYear;
      }).length;
      
      // 获取本周的开始时间（周一）
      const getWeekStart = () => {
        const d = new Date(now);
        const day = d.getDay();
        const diff = d.getDate() - day + (day === 0 ? -6 : 1);
        return new Date(d.setDate(diff));
      };
      
      const weekStart = getWeekStart();
      
      // 本周完成的任务
      stats.weeklyCompleted = completedTasks.value.filter(task => {
        if (!task.completed_time) return false;
        const completedDate = new Date(task.completed_time);
        return completedDate >= weekStart;
      }).length;
      
      // 计算好评率（4星及以上）
      const goodRatings = ratedTasks.filter(task => task.rating >= 4).length;
      stats.goodRatingPercentage = ratedTasks.length > 0
        ? Math.round((goodRatings / ratedTasks.length) * 100)
        : 0;
    };

    // 查看任务详情
    const viewTaskDetail = async (task) => {
      try {
        // 先设置基本信息
        currentTask.value = {...task};
        
        // 如果有任务ID但缺少详细信息，尝试从后端获取完整信息
        if (task.id && (!task.contact_name || !task.contact_phone)) {
          loading.value = true;
          try {
            // 尝试获取详细信息
            const { data } = await dashboardService.getTaskDetail(task.id, 'cleaning');
            if (data.code === 200 && data.data) {
              // 合并详细信息
              const detailData = data.data;
              currentTask.value = {
                ...currentTask.value,
                contact_name: detailData.contact_name || detailData.contactName || currentTask.value.contact_name || '未指定',
                contact_phone: detailData.contact_phone || detailData.contactPhone || currentTask.value.contact_phone || '未指定',
                expected_service_date: detailData.expected_service_date || detailData.expectedServiceDate || currentTask.value.expected_service_date,
                expected_time_slot: detailData.expected_time_slot || detailData.expectedTimeSlot || currentTask.value.expected_time_slot || '全天',
                special_requirements: detailData.special_requirements || detailData.specialRequirements || currentTask.value.special_requirements || '标准保洁服务',
                address: detailData.address || detailData.unit_info || currentTask.value.address,
                completed_time: detailData.completed_time || detailData.completionTime || detailData.completion_time || currentTask.value.completed_time,
                rating: detailData.rating || currentTask.value.rating || 0,
                review_content: detailData.review_content || detailData.reviewContent || currentTask.value.review_content || ''
              };
            }
          } catch (error) {
            console.error('获取任务详情失败:', error);
            // 即使获取详情失败，也继续显示已有信息
          } finally {
            loading.value = false;
          }
        }
        
        // 显示详情对话框
        detailDialogVisible.value = true;
      } catch (error) {
        console.error('处理任务详情失败:', error);
        ElMessage.error('获取任务详情失败');
      }
    };

    // 分页大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size;
      currentPage.value = 1; // 重置为第一页
      fetchCompletedTasks();
    };

    // 页码变化
    const handleCurrentChange = (page) => {
      currentPage.value = page;
      fetchCompletedTasks();
    };

    // 重置筛选条件
    const resetFilters = () => {
      filterStatus.value = '';
      ratingFilter.value = '';
      currentPage.value = 1;
      fetchCompletedTasks();
    };

    onMounted(() => {
      fetchCompletedTasks();
    });

    return {
      loading,
      completedTasks,
      total,
      currentPage,
      pageSize,
      filterStatus,
      ratingFilter,
      stats,
      detailDialogVisible,
      currentTask,
      fetchCompletedTasks,
      viewTaskDetail,
      handleSizeChange,
      handleCurrentChange,
      resetFilters
    };
  }
};
</script>

<style scoped>
.history-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
  padding: 10px 0;
}

.stat-card {
  height: 90px;
  margin-bottom: 5px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  margin-right: 15px;
}

.cleaning-icon {
  background-color: #67C23A;
}

.star-icon {
  background-color: #E6A23C;
}

.rating-icon {
  background-color: #F7BA2A;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 22px;
  font-weight: bold;
  color: #303133;
}

/* 单个工种统计样式 */
.stat-box {
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-box-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
}

.stat-box-value {
  font-size: 28px;
  font-weight: bold;
  color: #67C23A;
}
</style> 